/**
 * Rudimentary items
 */

import { removeEntity, Types, defineComponent, defineQuery } from './ecs';
import { cleanup } from './cleanup';
import { placeOnMap } from './pos2';
import { Glyph, Description } from './components';
import { log } from './log';
import { registerAction } from './actions';
import { describe } from '$lib';
import { registerOnTick } from './clock';
import { Clock } from './clock';
import { fromTemplate } from './builder';

export const Item = defineComponent('Item', {});

export const Rot = defineComponent('Rot', {
  lifespan: Types.ui32,
});

const rotQuery = defineQuery([Rot, Clock]);

export const apple = [
  [Glyph, {
    glyph: '%',
    color: '#5d0',
  }],
  [Description, {
    summary: 'apple',
    description: 'A common fruit.',
  }],
  [Item],
  [Clock, {
    created: 0, // FIXME
    time: 0,
  }],
  [Rot, {
    lifespan: 20,
  }],
];

export const addApple = (world) => {
  const e = fromTemplate(world, apple);
  placeOnMap(world, e, 7, 7);
  return e;
};

registerOnTick((world) => {
  const items = rotQuery(world);
  for (let item of items) {
    if (Rot.lifespan[item] <= Clock.time[item]) {
      log(`${describe(world, item)} rotted completely`);
      cleanup(world, item);
      removeEntity(world, item);
    }
  }
  return world;
});
